package com.yjkf.zh.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.iot.model.v20180120.InvokeThingServiceRequest;
import com.aliyuncs.iot.model.v20180120.InvokeThingServiceResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.yjkf.zh.admin.dao.SysUserDeviceMapper;
import com.yjkf.zh.admin.model.SysUser;
import com.yjkf.zh.admin.model.SysUserDevice;
import com.yjkf.zh.core.http.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 设备下设
 */
@RestController
@RequestMapping("/deviceSd")
public class SysDeviceSdCollect {

    @Autowired
    private SysUserDeviceMapper sysUserDeviceMapper;


    //方法一，API下设


    //方法二,构造下设
    // ===================需要用户填写的参数开始===========================
    // 修改Config.*的参数为您的实际信息
    // 站点id，根据实际站点获取对应id，https://help.aliyun.com/document_detail/40654.html
    private static String regionId = "cn-shanghai";
    // 用户账号AccessKey
    private static String accessKeyID = "LTAI15a7DBp6ScmD";
    // 用户账号AccesseKeySecret
    private static String accessKeySecret = "oLSe0uvSamvGQvMEmN2hAGawdJ4W4g";
    // 产品productKey，设备证书信息之一
    // private static String productKey = "a1jhwQkAWDQ";
    private static String productKey="a1UTv0vmM7k";

    // 设备名称deviceName，设备证书信息之一
    // private static String deviceName = "zh_demo01";
    private static String deviceName = "iot_tc";
    //private static  String ident= "F_MODBUS_16";
    private static  String ident= "sync_service";

    /**
     * 1、启动SyncServiceProcessor模拟设备在线 <br>
     * 2、启动本程序发起服务调用 <br>
     *
     * @param
     * @throws ServerException
     * @throws ClientException
     */
    @PostMapping("/setDeviceDown")
    public HttpResult setDeviceDown() throws ServerException, ClientException{
        // 获取服务端请求客户端
        DefaultAcsClient client = null;
        try {
            IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyID, accessKeySecret);
            DefaultProfile.addEndpoint(regionId, regionId, "Iot", "iot." + regionId + ".aliyuncs.com");
            client = new DefaultAcsClient(profile);
        } catch (Exception e) {
            System.out.println("create Open API Client failed !! exception:" + e.getMessage());
        }

        // 填充服务调用的参数
        InvokeThingServiceRequest request = new InvokeThingServiceRequest();
        request.setProductKey(productKey); // 设备证书之productKey
        request.setDeviceName(deviceName); // 设备证书之deviceName
        request.setIdentifier(ident); // 要调用的服务标识符，取决于服务定义
        JSONObject json = new JSONObject(); // 构造服务入参，服务入参是一个JSON String
        //  json.put("MyService2", 35); // 取决于服务定义，取值要符合服务定义时配置的参数规格
        json.put("F_MODBUS_16_YBDI",0x01);      //设备地址
        json.put("F_MODBUS_16_GNM",0x04);       //
        json.put("F_MODBUS_16_QSDZA",0x00);
        json.put("F_MODBUS_16_GS",0x06);
        json.put("F_MODBUS_16_ZJS",0x00);
        json.put("F_MODBUS_16_SJ",0x01);
        json.put("F_MODBUS_16_CRC16",0xD1CB);       //校验码

        request.setArgs(json.toString());
        //   request.setArgs(objects.toString());
        System.out.println(json.toString());
        // 获得服务调用响应
        InvokeThingServiceResponse response = client.getAcsResponse(request);
        if (response == null) {
            System.out.println("调用服务异常");
            return HttpResult.error("错误");
        }
        if (response != null && response.getSuccess()) { // 服务调用成功，仅代表发送服务指令的成功，不代表执行服务本身是否成功
                return HttpResult.ok("调用成功！");
        } else {
                return HttpResult.error("错误发生了！");
        }
    }

    @PostMapping("/devicesd")
    public HttpResult devicesd(@RequestParam Long userDeviceId,@RequestParam Long channelId) throws ServerException, ClientException{

        //获取创建时间大于当前设备的数量
        SysUserDevice sysUserDevice = sysUserDeviceMapper.getDeviceId(userDeviceId);
        List<SysUserDevice> sysUserDevices = sysUserDeviceMapper.findListForDate(sysUserDevice);
        int ployde = sysUserDevices.size()+1;
       int chid=Integer.parseInt(Integer.toHexString(channelId.intValue()*17));
        int signalTypes = 1000+chid;
        // 获取服务端请求客户端
        DefaultAcsClient client = null;
        try {
            IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyID, accessKeySecret);
            DefaultProfile.addEndpoint(regionId, regionId, "Iot", "iot." + regionId + ".aliyuncs.com");
            client = new DefaultAcsClient(profile);
        } catch (Exception e) {
            System.out.println( e.getMessage());
        }

        // 填充服务调用的参数
        InvokeThingServiceRequest request = new InvokeThingServiceRequest();
        request.setProductKey(productKey); // 设备证书之productKey
        request.setDeviceName(deviceName); // 设备证书之deviceName
        request.setIdentifier(ident); // 要调用的服务标识符，取决于服务定义
        JSONObject json = new JSONObject(); // 构造服务入参，服务入参是一个JSON String
        //  json.put("MyService2", 35); // 取决于服务定义，取值要符合服务定义时配置的参数规格
        json.put("F_MODBUS_16_YBDI",ployde);      //设备地址
        json.put("F_MODBUS_16_GNM",3);       //
      //  json.put("F_MODBUS_16_QSDZA",0x00);

      //  json.put("F_MODBUS_16_ZJS",0x00);
        json.put("F_MODBUS_16_SJ",signalTypes);
        json.put("F_MODBUS_16_GS",0021);
        // json.put("F_MODBUS_16_CRC16",0xD1CB);       //校验码

        request.setArgs(json.toString());
        //   request.setArgs(objects.toString());
        System.out.println(json.toString());
        // 获得服务调用响应
        InvokeThingServiceResponse response = client.getAcsResponse(request);
        if (response == null) {
            System.out.println("调用服务异常");
            return HttpResult.error("错误");
        }
        if (response != null && response.getSuccess()) { // 服务调用成功，仅代表发送服务指令的成功，不代表执行服务本身是否成功
            return HttpResult.ok("调用成功！");
        } else {
            return HttpResult.error("错误发生了！");
        }
    }

    public static  void main(String[] args){
            Long channelId = 2L;
        int chid=Integer.parseInt(Integer.toHexString(channelId.intValue()*17));
        int signalTypes = 1000+chid;
        System.out.println(signalTypes);
        System.out.println(0x1022);
    }
    }

